package com.kexio.auth.filter;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.kexio.auth.satoken.SaTokenStpInterfaceImpl;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;

/**
 * 请求缓存清理过滤器
 * 
 * 职责：在每个HTTP请求结束后，清理ThreadLocal中的缓存数据，防止内存泄漏
 * 
 * 背景：
 * - SaTokenStpInterfaceImpl 使用 ThreadLocal 缓存同一请求中的用户权限信息
 * - ThreadLocal 必须在请求结束后手动清理，否则在线程池环境下会导致内存泄漏
 * 
 * 执行顺序：
 * - @Order(Ordered.HIGHEST_PRECEDENCE + 100) 确保在其他过滤器之后执行清理
 * - 使用 try-finally 确保即使发生异常也能清理缓存
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 100)
public class RequestCacheCleanupFilter implements Filter {
    
    private static final Logger logger = LoggerFactory.getLogger(RequestCacheCleanupFilter.class);
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
            throws IOException, ServletException {
        try {
            // 继续执行后续过滤器和请求处理
            chain.doFilter(request, response);
        } finally {
            // 清理ThreadLocal缓存
            try {
                SaTokenStpInterfaceImpl.clearRequestCache();
                logger.trace("请求缓存已清理");
            } catch (Exception e) {
                logger.warn("清理请求缓存失败: {}", e.getMessage());
            }
        }
    }
}

